package wangjg.commons.bean;

import java.util.Comparator;

/**
 * 根据多个属性排序
 * @author wangjg
 *
 */
@SuppressWarnings({"rawtypes","unchecked"})
class BeanComparator2 implements Comparator{
	private String[] orderBy;
	private boolean[] asc;
	
	public BeanComparator2(String[] orderBy, boolean[] asc) {
		this.orderBy = orderBy;
		this.asc = asc;
	}

	public BeanComparator2(String orderExp) {
		String[] ss = orderExp.split(",");
		this.orderBy = new String[ss.length];
		this.asc = new boolean[ss.length];
		
		for(int i=0;i<ss.length;i++){
			String[] s = ss[i].split(" ");
			orderBy[i] = s[0];
			asc[i] = Boolean.parseBoolean(s[1]);
		}
	}

	public int compare(Object bean1, Object bean2) {
		StringBuilder sb1 = new StringBuilder();
		StringBuilder sb2 = new StringBuilder();
		for(int i=0;i<orderBy.length;i++){
			Object pv1 = BeanUtil.getProperty(bean1, orderBy[i]);
			Object pv2 = BeanUtil.getProperty(bean2, orderBy[i]);
			char code ;
			if(pv1 instanceof Comparable && pv2 instanceof Comparable){
				Comparable c1 = (Comparable)pv1;
				Comparable c2 = (Comparable)pv2;
				int cp = c1.compareTo(c2);

				if(asc!=null && Boolean.FALSE.equals(asc[i])){
					cp *= -1;
				}
				
				if(cp>0){
					code = '2';
				}else if(cp<0){
					code = '0';
				}else{
					code = '1';
				}
			}else{
				code = '1';
			}
			sb1.append(code);
			sb2.append('1');
		}
		return sb1.toString().compareTo(sb2.toString());
	}
}
